<template>
	<view class="salary-container">
		<!-- 顶部导航栏 -->
		<u-navbar bgColor="#F5F9FC" :placeholder="true" :border="true" height="48px">
			<view slot="left" class="navbar-left">
				<navigator url="/pageNew/salary/salary" class="back-button">
					<view class="nav-back-content">
						<u-icon color="#1e88e5" name="arrow-left" size="20"></u-icon>
						<view class="nav-title">员工工资管理</view>
					</view>
				</navigator>
			</view>
		</u-navbar>

		<!-- 年月选择器区域 -->
		<view class="year-picker-container">
			<picker mode="selector" :range="yearRange" :value="yearIndex" @change="handleYearChange"
				class="year-picker">
				<view class="year-display selected" style="display: flex;">
					<view>{{ yearRange[yearIndex] }}</view>
					<view style="margin-left: 10rpx;">
						<u-icon color="#ffffff" name="list-dot" size="22"></u-icon>
					</view>
				</view>
			</picker>
		</view>

		<scroll-view class="month-slider" scroll-x="true" :scroll-left="scrollInto">
			<view v-for="(month, index) in monthRange" :key="month.value" class="month-tab"
				:class="{ 'month-tab-selected': selectedMonthIndex === index }" @click="selectMonth(index)">
				{{ month.text }}
			</view>
		</scroll-view>

		<!-- 筛选与操作区 - 固定顶部 -->
		<view class="filter-bar">
			<view class="status-tabs">
				<view class="status-tab" :class="{active: currentStatus === 'active'}" @click="switchStatus('active')">
					在职</view>
				<view class="status-tab" :class="{active: currentStatus === 'inactive'}"
					@click="switchStatus('inactive')">离职</view>
			</view>
			<view class="action-buttons">
				<view class="action-btn send-salary" @click="sendSalarySheet">发送工资表</view>
				<view class="action-btn batch-edit" @click="enterBatchEdit" v-if="!isBatchEdit">批量编辑</view>
				<view class="action-btn cancel-select" @click="exitBatchEdit" v-if="isBatchEdit">取消选择</view>
			</view>
		</view>

		<!-- 员工工资列表 - 可滚动区域 -->
		<view class="salary-list">
			<!-- 加载状态 -->
			<view v-if="isLoading" class="loading-container">
				<u-loading-icon size="30" color="#1677ff"></u-loading-icon>
				<view class="loading-text">加载中...</view>
			</view>

			<!-- 空状态提示（没有符合条件的员工时显示） -->
			<view v-if="formattedEmployees.length === 0 && !isLoading" class="empty-container">
				<u-icon name="empty" size="60" color="#c0c4cc"></u-icon>
				<view class="empty-text">暂无{{ selectedYear }}年{{ selectedMonthIndex + 1 }}月工资数据</view>
				<view class="empty-tip">该月份暂无符合条件的在职员工</view>
			</view>

			<u-checkbox-group v-model="checkboxValue" @change="checkboxGroupChange" placement="column"
				v-if="isBatchEdit && formattedEmployees.length > 0">
				<view class="list-item" v-for="(item, index) in formattedEmployees" :key="item.uniqueKey">
					<!-- 员工基本信息 -->
					<view class="employee-header">
						<view class="name-status">
							<view class="employee-name">{{ item.name }}</view>
							<view class="month">{{ item.month }}月</view>
							<view class="status-tag" :class="item.tagClass">
								<u-icon :name="item.tagIcon" size="12" class="status-icon" />
								{{ item.tagText }}
							</view>
						</view>
					</view>

					<!-- 工资详情 -->
					<view class="salary-details">
						<view v-for="(salaryItem, idx) in salaryItems" :key="salaryItem.itemId">
							<view class="detail-row" v-if="salaryItem.isIncome">
								<view class="detail-label">{{ salaryItem.itemName }}</view>
								<view class="detail-value">{{ (item[salaryItem.fieldName] || 0).toFixed(2) }}</view>
							</view>
						</view>

						<view class="divider"></view>

						<view v-for="(salaryItem, idx) in salaryItems" :key="salaryItem.itemId">
							<view class="detail-row" v-if="!salaryItem.isIncome">
								<view class="detail-label">{{ salaryItem.itemName }}</view>
								<view class="detail-value">{{ (item[salaryItem.fieldName] || 0).toFixed(2) }}</view>
							</view>
						</view>

						<view class="divider"></view>
						<view class="detail-row total-row">
							<view class="detail-label">应发工资</view>
							<view class="detail-value">{{ item.payableSalary.toFixed(2) }}</view>
						</view>
						<view class="detail-row total-row">
							<view class="detail-label">实发工资</view>
							<view class="detail-value">{{ item.actualSalary.toFixed(2) }}</view>
						</view>
					</view>

					<!-- 批量选择框 - 居中显示 -->
					<view class="batch-checkbox-group">
						<u-checkbox :name="item.uniqueKey" shape="circle" class="batch-checkbox" />
					</view>
				</view>
			</u-checkbox-group>

			<!-- 非批量编辑模式下的列表 -->
			<view v-else-if="formattedEmployees.length > 0">
				<view class="list-item" v-for="(item, index) in formattedEmployees" :key="item.uniqueKey">
					<!-- 员工基本信息 -->
					<view class="employee-header">
						<view class="name-status">
							<view class="employee-name">{{ item.name }}</view>
							<view class="month">{{ item.month }}月</view>
							<view class="status-tag" :class="item.tagClass">
								<u-icon :name="item.tagIcon" size="12" class="status-icon" />
								{{ item.tagText }}
							</view>
						</view>
					</view>

					<!-- 工资详情 -->
					<view class="salary-details">
						<view v-for="(salaryItem, idx) in salaryItems" :key="salaryItem.itemId">
							<view class="detail-row" v-if="salaryItem.isIncome">
								<view class="detail-label">{{ salaryItem.itemName }}</view>
								<view class="detail-value">{{ (item[salaryItem.fieldName] || 0).toFixed(2) }}</view>
							</view>
						</view>

						<view class="divider"></view>

						<view v-for="(salaryItem, idx) in salaryItems" :key="salaryItem.itemId">
							<view class="detail-row" v-if="!salaryItem.isIncome">
								<view class="detail-label">{{ salaryItem.itemName }}</view>
								<view class="detail-value">{{ (item[salaryItem.fieldName] || 0).toFixed(2) }}</view>
							</view>
						</view>

						<view class="divider"></view>
						<view class="detail-row total-row">
							<view class="detail-label">应发工资</view>
							<view class="detail-value">{{ item.payableSalary.toFixed(2) }}</view>
						</view>
						<view class="detail-row total-row">
							<view class="detail-label">实发工资</view>
							<view class="detail-value">{{ item.actualSalary.toFixed(2) }}</view>
						</view>
					</view>

					<!-- 操作按钮组 -->
					<view class="action-buttons-group">
						<!-- 编辑按钮 -->
						<view class="operate-button edit-button" @click="editSalary(item)">
							<u-icon name="edit-pen" size="18" color="#1677ff" />
							<view class="button-text">编辑</view>
						</view>

						<!-- 确认录入按钮（仅未录入的记录显示） -->
						<view class="operate-button confirm-enter-button" @click="confirmSingleEnter(item)"
							v-if="item.isCalculated">
							<u-icon name="plus-circle" size="18" color="#52c41a" />
							<view class="button-text">确认录入</view>
						</view>

						<!-- 工资确认按钮（仅已录入但未确认的记录显示） -->
						<view class="operate-button confirm-salary-button" @click="confirmSingleSalary(item)"
							v-if="!item.isCalculated && item.status === 'unconfirmed'">
							<u-icon name="checkmark-circle" size="18" color="#fa8c16" />
							<view class="button-text">工资确认</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 批量操作底部栏 - 固定底部 -->
		<view class="batch-action-bar" v-if="isBatchEdit">
			<view class="selected-count">已选 {{ selectedCount }} 人</view>
			<view class="action-group">
				<view class="batch-btn delete-btn" @click="deleteSelected">
					<u-icon name="trash" size="16" class="btn-icon" />
					删除
				</view>
				<view class="batch-btn confirm-enter-btn" @click="batchConfirmEnter">
					<u-icon name="plus-circle" size="16" class="btn-icon" />
					录入
				</view>
				<view class="batch-btn confirm-salary-btn" @click="batchConfirmSalary">
					<u-icon name="checkmark-circle" size="16" class="btn-icon" />
					确认
				</view>
			</view>
		</view>

		<!-- 底部统计信息 - 固定底部 -->
		<view class="stats-container" v-if="!isBatchEdit && formattedEmployees.length > 0">
			<view class="stats-bar">
				<view class="total-people">共 {{ filteredEmployees.length }} 人</view>
				<view class="stats-values">
					<view class="stat-item">
						<span class="stat-label">社保</span>
						<span class="stat-number">{{ totalSocialSecurity.toFixed(2) }}</span>
					</view>
					<view class="stat-item">
						<span class="stat-label">公积金</span>
						<span class="stat-number">{{ totalHousingFund.toFixed(2) }}</span>
					</view>
					<view class="stat-item">
						<span class="stat-label">应发工资</span>
						<span class="stat-number">{{ totalPayableSalary.toFixed(2) }}</span>
					</view>
				</view>
			</view>
		</view>

		<!-- 添加按钮 -->
		<view class="add-button" @click="addEmployee">
			<u-icon name="plus" size="22" color="#fff" />
		</view>

		<!-- 编辑弹窗 -->
		<u-popup :show="editPopupVisible" v-if="editPopupVisible" mode="center" :round="10">
			<view class="edit-popup">
				<view class="popup-title">{{ editingItem.isCalculated ? '编辑未录入工资' : '编辑已录入工资' }}</view>

				<view class="form-group">
					<view class="form-label">员工姓名</view>
					<view class="form-value">{{ editingItem.name }}</view>
				</view>

				<view class="form-group">
					<view class="form-label">月份</view>
					<view class="form-value">{{ editingItem.month }}月</view>
				</view>

				<view v-for="(salaryItem, idx) in salaryItems" :key="salaryItem.itemId">
					<view class="form-group">
						<view class="form-label">{{ salaryItem.itemName }}</view>
						<u-input v-model.number="editingItem[salaryItem.fieldName]" type="number"
							:placeholder="'请输入' + salaryItem.itemName" />
					</view>
				</view>

				<view class="form-actions">
					<view class="cancel-btn" @click="editPopupVisible = false">取消</view>
					<view class="save-btn" @click="saveEdit">保存</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				companyInfo: uni.getStorageSync('companyInfo'),
				http: uni.$u.http, // 统一请求实例
				isBatchEdit: false,
				selectedCount: 0,
				currentStatus: 'active', // 'active' 在职, 'inactive' 离职
				checkboxValue: [], // 存储选中的checkbox的name值
				employees: [], // 原始员工工资数据
				pageParams: {
					pageNum: 1,
					pageSize: 1000 // 批量加载较多数据
				},
				salaryItems: [], // 从后台获取的工资项列表
				salaryItemMap: {}, // 工资项ID映射表（动态构建）
				socialRules: {}, // 社保公积金规则 { type: { companyRatio, personalRatio, minBase, maxBase } }

				// 关键：统一工资项ID映射（对应接口返回的id）
				incomeItemIds: {
					basicSalary: "1", // 基本工资
					performanceBonus: "2" // 绩效奖金
				},
				deductionItemIds: {
					pension: "4", // 养老保险（个人）
					medical: "5", // 医疗保险（个人）
					housingFund: "7", // 住房公积金（个人）
					unemployment: "1990994050818953218", // 失业保险（个人）
					incomeTax: "8" // 个人所得税
				},

				// 年月选择相关数据
				yearRange: [], // 年份选择范围
				yearIndex: 0, // 当前选中的年份索引
				selectedYear: '', // 选中的年份
				monthRange: [], // 月份选择范围
				selectedMonthIndex: 0, // 当前选中的月份索引
				scrollInto: 0, // 月份滚动位置
				screenWidth: uni.getSystemInfoSync().screenWidth * 2, // 屏幕宽度（rpx）
				monthWidth: 170, // 每个月份标签宽度（rpx）
				isFirstLoad: true, // 是否首次加载
				currentYear: new Date().getFullYear(), // 系统当前年份
				currentMonth: new Date().getMonth() + 1, // 系统当前月份（1-12）
				isLoading: false, // 加载状态标识

				// 编辑弹窗相关
				editPopupVisible: false,
				editingItem: {}, // 正在编辑的工资项
				currentCompanyId: '' // 当前公司ID
			};
		},
		computed: {
			// 获取公司ID
			companyId() {
				return this.companyInfo.id || '1986303016356728834';
			},
			// 格式化员工数据，添加统一uniqueKey
			formattedEmployees() {
				return this.employees.map(item => {
					// 计算状态标签相关属性
					let tagClass, tagIcon, tagText;
					if (item.isCalculated) {
						// 未录入状态
						tagClass = 'unentered';
						tagIcon = 'clock';
						tagText = '未录入';
					} else {
						if (item.status === 'confirmed') {
							// 已确认状态
							tagClass = 'confirmed';
							tagIcon = 'checkmark-circle';
							tagText = '已确认';
						} else {
							// 待确认状态
							tagClass = 'unconfirmed';
							tagIcon = 'warning';
							tagText = '待确认';
						}
					}

					return {
						...item,
						// 统一唯一标识
						uniqueKey: item.salarySummaryId ? `summary_${item.salarySummaryId}` : `emp_${item.id}`,
						// 状态标签属性
						tagClass,
						tagIcon,
						tagText
					};
				});
			},
			// 根据在职/离职状态筛选员工（已修复：匹配转换后的 employmentStatus）
			filteredEmployees() {
				return this.formattedEmployees.filter(emp => emp.employmentStatus === this.currentStatus);
			},
			// 计算筛选后员工的总社保金额（养老+医疗+失业）
			totalSocialSecurity() {
				const socialItemIds = [
					this.deductionItemIds.pension,
					this.deductionItemIds.medical,
					this.deductionItemIds.unemployment
				];
				return this.filteredEmployees.reduce((sum, emp) => {
					return socialItemIds.reduce((itemSum, id) => {
						const item = this.salaryItems.find(i => i.itemId === id);
						return itemSum + (item ? (emp[item.fieldName] || 0) : 0);
					}, sum);
				}, 0);
			},
			// 计算筛选后员工的总公积金金额
			totalHousingFund() {
				return this.filteredEmployees.reduce((sum, emp) => {
					const housingItem = this.salaryItems.find(item => item.itemId === this.deductionItemIds
						.housingFund);
					return sum + (housingItem ? (emp[housingItem.fieldName] || 0) : 0);
				}, 0);
			},
			// 计算筛选后员工的总应发工资
			totalPayableSalary() {
				return this.filteredEmployees.reduce((sum, emp) => sum + emp.payableSalary, 0);
			}
		},
		onLoad() {
			// 校验公司ID
			if (!this.companyId) {
				uni.showToast({
					title: '请先选择公司',
					icon: 'none'
				});
				uni.navigateBack();
				return;
			}
			this.currentCompanyId = this.companyId;

			// 先加载工资项配置和社保规则
			Promise.all([this.loadSalaryItems(), this.loadSocialRules()])
				.then(() => {
					// 初始化年月选择器
					this.initYearRange();
					this.initMonthRange();
					this.calculateScrollPosition();
					this.isFirstLoad = false;

					// 加载选中年月的工资数据
					this.loadSalaryData();
				})
				.catch(error => {
					console.error('初始化失败:', error);
					uni.showToast({
						title: '初始化失败',
						icon: 'none'
					});
				});
		},
		methods: {
			// 从员工remark中提取基本工资
			extractBasicSalary(remark) {
				if (!remark) return 0;
				const match = remark.match(/基本工资:(\d+)/);
				return match ? Number(match[1]) : 0;
			},

			// 从工资项remark中提取比例
			extractRatioFromRemark(remark) {
				if (!remark) return 0;
				const match = remark.match(/(\d+(?:\.\d+)?)%/);
				return match ? Number(match[1]) / 100 : 0;
			},

			// 加载社保公积金规则
			async loadSocialRules() {
				try {
					const res = await this.http.get('/VipSocialRule/list', {
						params: {
							companyId: this.companyId,
							pageSize: 100
						}
					});

					if (res.code === 200 && res.data?.data) {
						// 构建规则映射: key为规则类型(1=养老,2=公积金,3=医疗,4=失业)
						res.data.data.forEach(rule => {
							this.socialRules[rule.socialType] = {
								companyRatio: rule.companyRatio || 0,
								personalRatio: rule.personalRatio || 0,
								minBase: rule.baseMin || 0,
								maxBase: rule.baseMax || 0
							};
						});
					} else {
						// 加载失败时使用默认规则
						console.warn('加载社保公积金规则失败，使用默认配置');
						this.useDefaultSocialRules();
					}
				} catch (error) {
					console.error('加载社保公积金规则失败:', error);
					// 加载失败时使用默认规则
					this.useDefaultSocialRules();
				}
			},

			// 使用默认社保公积金规则
			useDefaultSocialRules() {
				this.socialRules = {
					// 1: 养老保险（对应itemId:4）
					1: {
						companyRatio: 0.16,
						personalRatio: 0.08,
						minBase: 3676,
						maxBase: 18378
					},
					// 2: 公积金（对应itemId:7）
					2: {
						companyRatio: 0.05,
						personalRatio: 0.05,
						minBase: 2200,
						maxBase: 28221
					},
					// 3: 医疗保险（对应itemId:5）
					3: {
						companyRatio: 0.08,
						personalRatio: 0.02,
						minBase: 3676,
						maxBase: 18378
					},
					// 4: 失业保险（对应itemId:1990994050818953218）
					4: {
						companyRatio: 0.005,
						personalRatio: 0.005,
						minBase: 3676,
						maxBase: 18378
					}
				};
			},

			// 加载工资项配置（核心：使用接口返回的id作为itemId）
			async loadSalaryItems() {
				try {
					const res = await this.http.get('/VipSalaryItem/list', {
						params: {
							companyId: this.companyId,
							pageSize: 1000
						}
					});

					if (res.code === 200 && res.data?.data) {
						// 处理工资项数据：统一itemId为接口返回的id（字符串类型）
						this.salaryItems = res.data.data.map((item, index) => {
							const fieldName = `salaryItem_${item.id}`;
							// 构建映射关系（key为接口返回的id）
							this.salaryItemMap[item.id] = {
								fieldName,
								index,
								ratio: this.extractRatioFromRemark(item.remark)
							};
							return {
								...item,
								itemId: item.id, // 明确设置itemId为接口返回的id
								fieldName,
								isIncome: item.itemType === 1, // itemType=1收入项，2扣除项
								ratio: this.extractRatioFromRemark(item.remark)
							};
						});

						// 按排序号排序
						this.salaryItems.sort((a, b) => a.sortOrder - b.sortOrder);
					} else {
						console.warn('加载工资项失败，使用默认配置');
						this.useDefaultSalaryItems();
					}
				} catch (error) {
					console.error('加载工资项配置失败:', error);
					this.useDefaultSalaryItems();
				}
			},

			// 使用默认工资项配置（与接口返回的id保持一致）
			useDefaultSalaryItems() {
				this.salaryItems = [{
						itemId: "1",
						itemName: "基本工资",
						itemType: 1,
						fieldName: 'salaryItem_1',
						isIncome: true,
						sortOrder: 1,
						ratio: 0
					},
					{
						itemId: "2",
						itemName: "绩效奖金",
						itemType: 1,
						fieldName: 'salaryItem_2',
						isIncome: true,
						sortOrder: 2,
						ratio: 0
					},
					{
						itemId: "4",
						itemName: "养老保险（个人）",
						itemType: 2,
						fieldName: 'salaryItem_4',
						isIncome: false,
						sortOrder: 4,
						ratio: 0.08 // 8%
					},
					{
						itemId: "5",
						itemName: "医疗保险（个人）",
						itemType: 2,
						fieldName: 'salaryItem_5',
						isIncome: false,
						sortOrder: 5,
						ratio: 0.02 // 2%
					},
					{
						itemId: "1990994050818953218",
						itemName: "失业保险（个人）",
						itemType: 2,
						fieldName: 'salaryItem_1990994050818953218',
						isIncome: false,
						sortOrder: 6,
						ratio: 0.005 // 0.5%
					},
					{
						itemId: "7",
						itemName: "住房公积金（个人）",
						itemType: 2,
						fieldName: 'salaryItem_7',
						isIncome: false,
						sortOrder: 7,
						ratio: 0.12 // 12%
					},
					{
						itemId: "8",
						itemName: "个人所得税",
						itemType: 2,
						fieldName: 'salaryItem_8',
						isIncome: false,
						sortOrder: 8,
						ratio: 0
					}
				];

				// 构建映射关系
				this.salaryItems.forEach(item => {
					this.salaryItemMap[item.itemId] = {
						fieldName: item.fieldName,
						index: this.salaryItems.indexOf(item),
						ratio: item.ratio
					};
				});
			},

			// 初始化年份范围
			initYearRange() {
				const currentYear = new Date().getFullYear();
				this.yearRange = [];
				// 生成近5年（当前年往前推4年）
				for (let i = currentYear; i >= currentYear - 4; i--) {
					this.yearRange.push(i + '年');
				}
				this.yearIndex = 0;
				this.selectedYear = currentYear.toString();
			},

			// 初始化月份范围
			initMonthRange() {
				this.monthRange = [];
				// 确定最大月份：当前年份只能选到当前月份，往年可以选到12月
				const maxMonth = this.selectedYear == this.currentYear ? this.currentMonth : 12;
				// 添加月份数据（1-最大月份）
				for (let i = 1; i <= maxMonth; i++) {
					this.monthRange.push({
						text: i + '月',
						value: i.toString()
					});
				}
				// 首次加载时选中当前月份，非首次加载确保索引有效
				if (this.isFirstLoad) {
					this.selectedMonthIndex = this.currentMonth - 1;
				} else {
					if (this.selectedMonthIndex >= this.monthRange.length) {
						this.selectedMonthIndex = this.monthRange.length - 1;
					}
				}
			},

			// 年份变更处理
			handleYearChange(e) {
				const prevIndex = this.yearIndex;
				this.yearIndex = e.detail.value;
				// 提取选中年份的纯数字（去除"年"字）
				this.selectedYear = this.yearRange[this.yearIndex].replace('年', '');
				// 保存当前选中的月份索引
				const currentSelectedIndex = this.selectedMonthIndex;
				// 重新初始化月份范围（根据新年份调整可选项）
				this.initMonthRange();
				// 恢复之前选中的月份索引（保持用户选择习惯）
				this.selectedMonthIndex = currentSelectedIndex;
				// 确保索引有效
				if (this.selectedMonthIndex >= this.monthRange.length) {
					this.selectedMonthIndex = this.monthRange.length - 1;
				}
				// 年份变更时重新加载工资数据（仅当年份真的改变时）
				if (prevIndex !== this.yearIndex) {
					this.loadSalaryData();
				}
			},

			// 月份选择处理
			selectMonth(index) {
				this.selectedMonthIndex = index;
				// 月份变更时重新加载工资数据
				this.loadSalaryData();
			},

			// 计算月份滚动位置（确保选中项居中）
			calculateScrollPosition() {
				const totalMonthWidth = this.monthRange.length * this.monthWidth;
				const screenHalfWidth = this.screenWidth / 2;
				const currentItemOffset = this.selectedMonthIndex * this.monthWidth;

				if (this.monthRange.length <= 1) {
					// 只有1个月份时不滚动
					this.scrollInto = 0;
				} else if (this.selectedMonthIndex === 0) {
					// 选中第1项时靠左
					this.scrollInto = 0;
				} else if (this.selectedMonthIndex === this.monthRange.length - 1) {
					// 选中最后1项时靠右
					this.scrollInto = totalMonthWidth - screenHalfWidth;
				} else {
					// 中间项居中显示
					this.scrollInto = currentItemOffset - screenHalfWidth;
				}
			},

			// 获取符合条件的员工（在选中年月前已入职）- 已修复：isOnJob转employmentStatus
			async getQualifiedEmployees(year, month) {
				try {
					// 1. 获取公司所有员工（根据在职状态筛选：直接传isOnJob参数，减少前端处理）
					const empRes = await this.http.get('/VipEmployee/list', {
						params: {
							companyId: this.companyId,
							isOnJob: this.currentStatus === 'active' ? 1 : 0, // 关键：接口直接筛选状态
							pageSize: 1000
						}
					});

					if (empRes.code !== 200 || !empRes.data?.data) {
						return [];
					}

					const allEmployees = empRes.data.data;
					const qualifiedEmployees = [];
					const targetDate = new Date(year, month - 1, 1); // 选中年月的第一天

					// 2. 筛选出在选中年月前已入职的员工，并转换isOnJob为employmentStatus
					for (const emp of allEmployees) {
						if (!emp.hireDate) continue;

						const hireDate = new Date(emp.hireDate);
						// 入职日期在选中年月之前，或者在当月入职
						if (hireDate <= targetDate ||
							(hireDate.getFullYear() === year && hireDate.getMonth() + 1 === month)) {
							// 核心修复1：将接口的isOnJob转换为前端需要的employmentStatus
							emp.employmentStatus = emp.isOnJob === 1 ? 'active' : 'inactive';
							qualifiedEmployees.push(emp);
						}
					}

					return qualifiedEmployees;
				} catch (error) {
					console.error('获取符合条件的员工失败:', error);
					return [];
				}
			},

			// 加载工资数据
			async loadSalaryData() {
				if (this.salaryItems.length === 0 || Object.keys(this.socialRules).length === 0) {
					// 等待工资项和社保规则加载完成
					await new Promise(resolve => {
						const check = setInterval(() => {
							if (this.salaryItems.length > 0 && Object.keys(this.socialRules).length >
								0) {
								clearInterval(check);
								resolve();
							}
						}, 100);
					});
				}

				try {
					this.isLoading = true;
					this.employees = [];

					const queryYear = parseInt(this.selectedYear);
					const queryMonth = this.selectedMonthIndex + 1;
					console.log(`加载 ${queryYear}年${queryMonth}月 工资数据（状态：${this.currentStatus}）`);

					// 1. 获取所有应该有工资记录的员工（已入职+对应在职/离职状态）
					const qualifiedEmployees = await this.getQualifiedEmployees(queryYear, queryMonth);
					if (qualifiedEmployees.length === 0) {
						this.isLoading = false;
						return;
					}

					// 2. 获取已有的工资汇总数据
					const summaryRes = await this.http.get('/VipSalarySummary/list', {
						params: {
							companyId: this.companyId,
							year: queryYear,
							month: queryMonth,
							pageSize: 1000
						}
					});

					const existingSummaries = summaryRes.code === 200 && summaryRes.data?.data ? summaryRes.data.data :
						[];

					// 3. 处理每个符合条件的员工
					for (const emp of qualifiedEmployees) {
						// 查找该员工是否已有工资记录
						const existingSummary = existingSummaries.find(s => s.employeeId === emp.id);

						if (existingSummary) {
							// 3.1 已有记录，加载详情
							const detailRes = await this.http.get('/VipSalaryItemDetail/list', {
								params: {
									salarySummaryId: existingSummary.id,
									companyId: this.companyId
								}
							});

							if (detailRes.code === 200 && detailRes.data?.data) {
								this.formatSalaryData(existingSummary, detailRes.data.data, emp);
							}
						} else {
							// 3.2 无记录，前端计算工资
							this.calculateSalaryForEmployee(emp, queryYear, queryMonth);
						}
					}
				} catch (error) {
					console.error('加载工资数据失败:', error);
					uni.showToast({
						title: '加载数据失败',
						icon: 'none'
					});
				} finally {
					this.isLoading = false;
				}
			},

			// 计算社保公积金基数（根据规则取基本工资与上下限的交集）
			calculateBase(salary, rule) {
				if (!rule) return 0;
				// 基数不能低于最低基数，不能高于最高基数
				return Math.max(rule.minBase, Math.min(salary, rule.maxBase));
			},

			// 前端计算工资（核心：根据itemId匹配工资项）- 已修复：employmentStatus赋值
			calculateSalaryForEmployee(employee, year, month) {
				// 创建员工工资对象
				const empSalary = {
					id: employee.id,
					employeeId: employee.id,
					name: employee.name || '未知员工',
					month: month,
					// 核心修复2：基于员工的isOnJob设置employmentStatus（兼容接口字段）
					employmentStatus: employee.employmentStatus || (employee.isOnJob === 1 ? 'active' : 'inactive'),
					isCalculated: true, // 标记为前端计算的记录（未录入数据库）
					companyId: this.currentCompanyId,
					payableSalary: 0, // 应发工资
					actualSalary: 0 // 实发工资
				};

				// 为每个工资项设置默认值（根据itemId匹配）
				this.salaryItems.forEach(item => {
					if (item.isIncome) {
						// 收入项默认值
						switch (item.itemId) {
							case this.incomeItemIds.basicSalary: // 基本工资
								empSalary[item.fieldName] = this.extractBasicSalary(employee.remark) || 5000;
								break;
							case this.incomeItemIds.performanceBonus: // 绩效奖金
								empSalary[item.fieldName] = 1000;
								break;
							default:
								empSalary[item.fieldName] = 0;
						}
					} else {
						// 扣除项默认值
						empSalary[item.fieldName] = 0;
					}
				});

				// 计算应发工资（所有收入项之和）
				const incomeItems = this.salaryItems.filter(item => item.isIncome);
				empSalary.payableSalary = incomeItems.reduce((sum, item) => {
					return sum + (empSalary[item.fieldName] || 0);
				}, 0);

				// 获取基本工资（用于计算社保公积金）
				const basicSalaryItem = this.salaryItems.find(item => item.itemId === this.incomeItemIds.basicSalary);
				const basicSalary = basicSalaryItem ? (empSalary[basicSalaryItem.fieldName] || 0) : 0;

				// 1. 计算养老保险（个人）- itemId:4
				const pensionItem = this.salaryItems.find(item => item.itemId === this.deductionItemIds.pension);
				const pensionRule = this.socialRules[1]; // 1=养老保险规则
				if (pensionItem) {
					const ratio = pensionItem.ratio || (pensionRule ? pensionRule.personalRatio : 0);
					if (pensionRule) {
						const pensionBase = this.calculateBase(basicSalary, pensionRule);
						empSalary[pensionItem.fieldName] = Number((pensionBase * ratio).toFixed(2));
					}
				}

				// 2. 计算医疗保险（个人）- itemId:5
				const medicalItem = this.salaryItems.find(item => item.itemId === this.deductionItemIds.medical);
				const medicalRule = this.socialRules[3]; // 3=医疗保险规则
				if (medicalItem) {
					const ratio = medicalItem.ratio || (medicalRule ? medicalRule.personalRatio : 0);
					if (medicalRule) {
						const medicalBase = this.calculateBase(basicSalary, medicalRule);
						empSalary[medicalItem.fieldName] = Number((medicalBase * ratio).toFixed(2));
					}
				}

				// 3. 计算失业保险（个人）- itemId:1990994050818953218
				const unemploymentItem = this.salaryItems.find(item => item.itemId === this.deductionItemIds.unemployment);
				const unemploymentRule = this.socialRules[4]; // 4=失业保险规则
				if (unemploymentItem) {
					const ratio = unemploymentItem.ratio || (unemploymentRule ? unemploymentRule.personalRatio : 0);
					if (unemploymentRule) {
						const unemploymentBase = this.calculateBase(basicSalary, unemploymentRule);
						empSalary[unemploymentItem.fieldName] = Number((unemploymentBase * ratio).toFixed(2));
					}
				}

				// 4. 计算住房公积金（个人）- itemId:7
				const housingItem = this.salaryItems.find(item => item.itemId === this.deductionItemIds.housingFund);
				const housingRule = this.socialRules[2]; // 2=公积金规则
				if (housingItem) {
					const ratio = housingItem.ratio || (housingRule ? housingRule.personalRatio : 0);
					if (housingRule) {
						const housingBase = this.calculateBase(basicSalary, housingRule);
						empSalary[housingItem.fieldName] = Number((housingBase * ratio).toFixed(2));
					}
				}

				// 5. 计算个人所得税 - itemId:8
				const taxItem = this.salaryItems.find(item => item.itemId === this.deductionItemIds.incomeTax);
				if (taxItem) {
					// 所有扣除项（除了个税）
					const deductionItemIds = [
						this.deductionItemIds.pension,
						this.deductionItemIds.medical,
						this.deductionItemIds.unemployment,
						this.deductionItemIds.housingFund
					];
					const totalDeduction = deductionItemIds.reduce((sum, id) => {
						const item = this.salaryItems.find(i => i.itemId === id);
						return sum + (item ? (empSalary[item.fieldName] || 0) : 0);
					}, 0);

					const taxableIncome = empSalary.payableSalary - totalDeduction - 5000; // 5000起征点
					empSalary[taxItem.fieldName] = taxableIncome > 0 ? Number((taxableIncome * 0.03).toFixed(2)) : 0;
				}

				// 计算实发工资
				const allDeductionItems = this.salaryItems.filter(item => !item.isIncome);
				const totalDeduction = allDeductionItems.reduce((sum, item) => {
					return sum + (empSalary[item.fieldName] || 0);
				}, 0);

				empSalary.actualSalary = Number((empSalary.payableSalary - totalDeduction).toFixed(2));
				empSalary.status = "unconfirmed"; // 未确认状态

				// 添加到员工列表
				this.employees.push(empSalary);
			},

			// 格式化工资数据（汇总+明细+员工信息）- 已修复：employmentStatus赋值
			formatSalaryData(summary, details, employee) {
				// 构建工资项映射（key: itemId，与接口返回一致）
				const detailMap = {};
				details.forEach(detail => {
					detailMap[detail.itemId] = detail.itemValue; // 这里的itemId是接口返回的字符串类型
				});

				// 组装前端显示数据
				const empSalary = {
					salarySummaryId: summary.id, // 工资汇总ID
					employeeId: summary.employeeId,
					name: employee.name || '未知员工',
					month: summary.month, // 从汇总数据中获取月份
					payableSalary: summary.totalIncome || 0,
					actualSalary: summary.actualSalary || 0,
					// 状态转换（0-未确认，1-已确认，2-已发放）
					status: summary.status === 1 ? 'confirmed' : 'unconfirmed',
					// 核心修复3：基于员工的isOnJob设置employmentStatus（匹配筛选条件）
					employmentStatus: employee.isOnJob === 1 ? 'active' : 'inactive',
					isCalculated: false, // 标记为数据库已有记录
					companyId: this.currentCompanyId
				};

				// 为每个工资项赋值（根据itemId匹配）
				this.salaryItems.forEach(item => {
					empSalary[item.fieldName] = detailMap[item.itemId] || 0;
				});

				this.employees.push(empSalary);
			},

			// 编辑工资记录（弹窗实现）
			editSalary(item) {
				// 深拷贝当前项数据用于编辑
				this.editingItem = JSON.parse(JSON.stringify(item));
				this.editPopupVisible = true;
			},

			// 保存编辑内容
			async saveEdit() {
				// 表单验证
				if (!this.editingItem.companyId) {
					uni.showToast({
						title: '公司信息不能为空',
						icon: 'none'
					});
					return;
				}

				// 重新计算应发和实发工资
				const incomeItems = this.salaryItems.filter(item => item.isIncome);
				this.editingItem.payableSalary = incomeItems.reduce((sum, item) => {
					return sum + (this.editingItem[item.fieldName] || 0);
				}, 0);

				const deductionItems = this.salaryItems.filter(item => !item.isIncome);
				const totalDeduction = deductionItems.reduce((sum, item) => {
					return sum + (this.editingItem[item.fieldName] || 0);
				}, 0);

				this.editingItem.actualSalary = Number((this.editingItem.payableSalary - totalDeduction).toFixed(2));

				try {
					// 更新本地数据
					const index = this.employees.findIndex(emp =>
						(emp.salarySummaryId && emp.salarySummaryId === this.editingItem.salarySummaryId) ||
						(emp.id === this.editingItem.id && emp.isCalculated)
					);

					if (index !== -1) {
						this.employees.splice(index, 1, this.editingItem);

						// 如果是已存在的记录，同步更新到服务器
						if (this.editingItem.salarySummaryId) {
							// 更新工资汇总表
							await this.http.put('/VipSalarySummary', {
								id: this.editingItem.salarySummaryId,
								totalIncome: this.editingItem.payableSalary,
								totalDeduction: totalDeduction,
								actualSalary: this.editingItem.actualSalary,
								companyId: this.currentCompanyId,
								updatedTime: new Date().toISOString()
							});

							// 获取当前汇总记录的所有明细
							const detailRes = await this.http.get('/VipSalaryItemDetail/list', {
								params: {
									salarySummaryId: this.editingItem.salarySummaryId,
									companyId: this.currentCompanyId
								}
							});

							// 准备要更新的明细数据
							const existingDetailIds = {};
							if (detailRes.code === 200 && detailRes.data?.data) {
								// 记录已存在的明细ID（key: itemId）
								detailRes.data.data.forEach(detail => {
									existingDetailIds[detail.itemId] = detail.id;
								});
							}

							// 处理每个工资项的明细（核心：传递itemId为接口返回的id）
							for (const item of this.salaryItems) {
								const itemValue = this.editingItem[item.fieldName] || 0;

								if (existingDetailIds[item.itemId]) {
									// 更新已有明细
									await this.http.put('/VipSalaryItemDetail', {
										id: existingDetailIds[item.itemId],
										salarySummaryId: this.editingItem.salarySummaryId,
										itemId: item.itemId, // 传递接口返回的itemId（字符串）
										itemValue: itemValue,
										companyId: this.currentCompanyId,
										updatedTime: new Date().toISOString()
									});
								} else {
									// 添加新明细
									await this.http.post('/VipSalaryItemDetail', {
										salarySummaryId: this.editingItem.salarySummaryId,
										itemId: item.itemId, // 传递接口返回的itemId（字符串）
										itemValue: itemValue,
										companyId: this.currentCompanyId
									});
								}
							}
						}

						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
						this.editPopupVisible = false;
					}
				} catch (error) {
					console.error('保存工资数据失败:', error);
					uni.showToast({
						title: '保存失败，请重试',
						icon: 'none'
					});
				}
			},

			// 单个确认录入（未录入→已录入，存入数据库）
			async confirmSingleEnter(item) {
				uni.showModal({
					title: '确认录入',
					content: `确定要将${item.name}的工资记录录入系统吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '处理中...'
								});

								// 获取当前选中的年月
								const queryYear = parseInt(this.selectedYear);
								const queryMonth = this.selectedMonthIndex + 1;

								// 生成payTime：格式 yyyy-MM-dd（兼容后端LocalDate）
								const payDate = new Date(queryYear, queryMonth - 1, 10);
								const payTime =
									`${payDate.getFullYear()}-${String(payDate.getMonth() + 1).padStart(2, '0')}-${String(payDate.getDate()).padStart(2, '0')}`;

								// 1. 创建工资汇总记录
								const summaryRes = await this.http.post('/VipSalarySummary', {
									companyId: this.currentCompanyId, // 保持字符串格式
									employeeId: item.employeeId, // 保持原有格式
									year: queryYear,
									month: queryMonth,
									totalIncome: item.payableSalary,
									totalDeduction: item.payableSalary - item.actualSalary,
									actualSalary: item.actualSalary,
									status: 0, // 0-待确认
									payTime: payTime
								});

								if (summaryRes.code === 200 && summaryRes.data) {
									const summaryId = summaryRes.data;
									// 2. 创建工资项明细记录（核心：itemId使用接口返回的id）
									const detailPromises = this.salaryItems.map(salaryItem => {
										return this.http.post('/VipSalaryItemDetail', {
											salarySummaryId: summaryId,
											itemId: salaryItem
												.itemId, // 传递接口返回的itemId（字符串）
											itemValue: item[salaryItem.fieldName] || 0,
											remark: salaryItem.itemName,
											companyId: this.currentCompanyId
										});
									});

									// 批量保存明细
									await Promise.all(detailPromises);

									uni.showToast({
										title: '录入成功',
										icon: 'success'
									});

									// 重新加载数据
									this.loadSalaryData();
								} else {
									throw new Error(summaryRes.msg || '创建汇总记录失败');
								}
							} catch (error) {
								console.error('确认录入失败:', error);
								uni.showToast({
									title: '录入失败：' + (error.message || error),
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			},

			// 单个工资确认（已录入→已确认，更新状态）
			async confirmSingleSalary(item) {
				uni.showModal({
					title: '工资确认',
					content: `确定要确认${item.name}${item.month}月的工资吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '处理中...'
								});

								// 已有汇总记录，更新状态
								await this.http.put('/VipSalarySummary', {
									id: item.salarySummaryId,
									status: 1, // 1-已确认
									companyId: this.currentCompanyId,
									updatedTime: new Date().toISOString(),
									updatedBy: uni.getStorageSync('userName') || 'admin'
								});

								uni.showToast({
									title: '确认成功',
									icon: 'success'
								});

								// 重新加载数据
								this.loadSalaryData();
							} catch (error) {
								console.error('工资确认失败:', error);
								uni.showToast({
									title: '确认失败，请重试',
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			},

			// 批量确认录入
			async batchConfirmEnter() {
				if (this.selectedCount === 0) {
					uni.showToast({
						title: '请先选择要录入的记录',
						icon: 'none'
					});
					return;
				}

				uni.showModal({
					title: '批量确认录入',
					content: `确定要将选中的 ${this.selectedCount} 条工资记录录入系统吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '处理中...'
								});

								const queryYear = parseInt(this.selectedYear);
								const queryMonth = this.selectedMonthIndex + 1;
								let successCount = 0;

								// 批量处理选中的记录
								for (const uniqueKey of this.checkboxValue) {
									const empSalary = this.formattedEmployees.find(item => item
										.uniqueKey === uniqueKey);

									if (empSalary && empSalary.isCalculated) {
										// 仅处理未录入的记录
										try {
											// 生成payTime
											const payDate = new Date(queryYear, queryMonth - 1, 10);
											const payTime =
												`${payDate.getFullYear()}-${String(payDate.getMonth() + 1).padStart(2, '0')}-${String(payDate.getDate()).padStart(2, '0')}`;

											// 创建工资汇总记录
											const summaryRes = await this.http.post('/VipSalarySummary', {
												companyId: this.currentCompanyId,
												employeeId: empSalary.employeeId,
												year: queryYear,
												month: queryMonth,
												totalIncome: empSalary.payableSalary,
												totalDeduction: empSalary.payableSalary - empSalary
													.actualSalary,
												actualSalary: empSalary.actualSalary,
												status: 0,
												payTime: payTime
											});

											if (summaryRes.code === 200 && summaryRes.data) {
												const summaryId = summaryRes.data;
												// 创建明细记录（itemId使用接口返回的id）
												const detailPromises = this.salaryItems.map(item => {
													return this.http.post('/VipSalaryItemDetail', {
														salarySummaryId: summaryId,
														itemId: item.itemId, // 接口返回的itemId
														itemValue: empSalary[item
															.fieldName] || 0,
														remark: item.itemName,
														companyId: this.currentCompanyId
													});
												});

												await Promise.all(detailPromises);
												successCount++;
											}
										} catch (error) {
											console.error(`录入失败：${empSalary.name}`, error);
										}
									}
								}

								uni.showToast({
									title: `成功录入 ${successCount}/${this.selectedCount} 条记录`,
									icon: 'success'
								});

								// 重置状态并重新加载数据
								this.checkboxValue = [];
								this.selectedCount = 0;
								this.isBatchEdit = false;
								this.loadSalaryData();
							} catch (error) {
								console.error('批量录入失败:', error);
								uni.showToast({
									title: '批量录入失败，请重试',
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			},

			// 批量工资确认
			async batchConfirmSalary() {
				if (this.selectedCount === 0) {
					uni.showToast({
						title: '请先选择要确认的记录',
						icon: 'none'
					});
					return;
				}

				uni.showModal({
					title: '批量工资确认',
					content: `确定要确认选中的 ${this.selectedCount} 条工资记录吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '处理中...'
								});

								let successCount = 0;

								// 批量处理选中的记录
								for (const uniqueKey of this.checkboxValue) {
									const empSalary = this.formattedEmployees.find(item => item
										.uniqueKey === uniqueKey);

									if (empSalary && !empSalary.isCalculated && empSalary.status ===
										'unconfirmed') {
										// 仅处理已录入但未确认的记录
										try {
											await this.http.put('/VipSalarySummary', {
												id: empSalary.salarySummaryId,
												status: 1, // 1-已确认
												companyId: this.currentCompanyId,
												updatedTime: new Date().toISOString(),
												updatedBy: uni.getStorageSync('userName') ||
													'admin'
											});
											successCount++;
										} catch (error) {
											console.error(`确认失败：${empSalary.name}`, error);
										}
									}
								}

								uni.showToast({
									title: `成功确认 ${successCount}/${this.selectedCount} 条记录`,
									icon: 'success'
								});

								// 重置状态并重新加载数据
								this.checkboxValue = [];
								this.selectedCount = 0;
								this.isBatchEdit = false;
								this.loadSalaryData();
							} catch (error) {
								console.error('批量确认失败:', error);
								uni.showToast({
									title: '批量确认失败，请重试',
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			},

			// 切换在职/离职状态
			switchStatus(status) {
				this.currentStatus = status;
				if (this.isBatchEdit) {
					this.exitBatchEdit();
				}
				// 切换状态后重新加载数据（核心：触发新状态的员工查询）
				this.loadSalaryData();
			},

			// 进入批量编辑模式
			enterBatchEdit() {
				this.isBatchEdit = true;
				this.checkboxValue = [];
				this.selectedCount = 0;
			},

			// 退出批量编辑模式
			exitBatchEdit() {
				this.isBatchEdit = false;
				this.checkboxValue = [];
				this.selectedCount = 0;
			},

			// 复选框组变化事件
			checkboxGroupChange(e) {
				this.checkboxValue = e;
				this.selectedCount = e.length;
			},

			// 删除选中的工资记录
			async deleteSelected() {
				if (this.selectedCount === 0) {
					uni.showToast({
						title: '请先选择要删除的记录',
						icon: 'none'
					});
					return;
				}

				uni.showModal({
					title: '确认删除',
					content: `确定要删除选中的 ${this.selectedCount} 条记录吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '删除中...'
								});

								// 从 uniqueKey 中提取真实的 salarySummaryId（用于删除）
								const salarySummaryIds = this.checkboxValue
									.filter(key => key.startsWith('summary_'))
									.map(key => key.replace('summary_', ''));

								// 批量删除工资汇总记录（明细会通过外键级联删除）
								if (salarySummaryIds.length > 0) {
									await this.http.delete(
										`/VipSalarySummary/${salarySummaryIds.join(',')}`);
								}

								// 删除本地临时数据（未保存到数据库的记录，uniqueKey 以 emp_ 开头）
								this.employees = this.employees.filter(emp => {
									const uniqueKey = emp.salarySummaryId ?
										`summary_${emp.salarySummaryId}` : `emp_${emp.id}`;
									return !this.checkboxValue.includes(uniqueKey);
								});

								// 重置选中状态
								this.checkboxValue = [];
								this.selectedCount = 0;

								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});

								// 如果删除后没有数据，退出批量编辑
								if (this.filteredEmployees.length === 0) {
									setTimeout(() => {
										this.isBatchEdit = false;
									}, 1000);
								}
							} catch (error) {
								console.error('删除工资记录失败:', error);
								uni.showToast({
									title: '删除失败，请重试',
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			},

			// 发送工资表
			async sendSalarySheet() {
				try {
					// 获取当前选中的年月
					const queryYear = parseInt(this.selectedYear);
					const queryMonth = this.selectedMonthIndex + 1;

					// 调用发送工资表接口
					const res = await this.http.post('/VipSalary/sendSalarySheet', {
						companyId: this.currentCompanyId,
						year: queryYear,
						month: queryMonth,
						employmentStatus: this.currentStatus
					});

					if (res.code === 200) {
						uni.showToast({
							title: '工资表发送成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: '发送失败：' + (res.msg || '未知错误'),
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('发送工资表失败:', error);
					uni.showToast({
						title: '发送失败，请重试',
						icon: 'none'
					});
				}
			},

			// 添加新员工工资记录（初始为未确认状态）
			async addEmployee() {
				// 获取当前选中的年月
				const queryYear = parseInt(this.selectedYear);
				const queryMonth = this.selectedMonthIndex + 1;

				// 生成临时ID
				const newEmpId = Math.max(...this.employees.map(emp => emp.employeeId || emp.id), 0) + 1;

				// 创建新员工工资对象（默认当前筛选状态的employmentStatus）
				const newEmp = {
					id: newEmpId,
					employeeId: newEmpId,
					name: "新员工",
					month: queryMonth,
					// 默认与当前筛选状态一致（在职/离职）
					employmentStatus: this.currentStatus,
					isOnJob: this.currentStatus === 'active' ? 1 : 0, // 同步接口字段
					isCalculated: true,
					companyId: this.currentCompanyId,
					// 设置默认基本工资在remark中
					remark: "基本工资:5000",
					payableSalary: 0,
					actualSalary: 0
				};

				// 为每个工资项设置默认值（根据itemId匹配）
				this.salaryItems.forEach(item => {
					if (item.isIncome) {
						switch (item.itemId) {
							case this.incomeItemIds.basicSalary: // 基本工资
								newEmp[item.fieldName] = this.extractBasicSalary(newEmp.remark) || 5000;
								break;
							case this.incomeItemIds.performanceBonus: // 绩效奖金
								newEmp[item.fieldName] = 1000;
								break;
							default:
								newEmp[item.fieldName] = 0;
						}
					} else {
						newEmp[item.fieldName] = 0;
					}
				});

				// 计算应发工资
				const incomeItems = this.salaryItems.filter(item => item.isIncome);
				newEmp.payableSalary = incomeItems.reduce((sum, item) => {
					return sum + (newEmp[item.fieldName] || 0);
				}, 0);

				// 获取基本工资（用于计算社保公积金）
				const basicSalaryItem = this.salaryItems.find(item => item.itemId === this.incomeItemIds.basicSalary);
				const basicSalary = basicSalaryItem ? (newEmp[basicSalaryItem.fieldName] || 0) : 0;

				// 1. 计算养老保险（个人）- itemId:4
				const pensionItem = this.salaryItems.find(item => item.itemId === this.deductionItemIds.pension);
				const pensionRule = this.socialRules[1];
				if (pensionItem && pensionRule) {
					const ratio = pensionItem.ratio || pensionRule.personalRatio;
					const pensionBase = this.calculateBase(basicSalary, pensionRule);
					newEmp[pensionItem.fieldName] = Number((pensionBase * ratio).toFixed(2));
				}

				// 2. 计算医疗保险（个人）- itemId:5
				const medicalItem = this.salaryItems.find(item => item.itemId === this.deductionItemIds.medical);
				const medicalRule = this.socialRules[3];
				if (medicalItem && medicalRule) {
					const ratio = medicalItem.ratio || medicalRule.personalRatio;
					const medicalBase = this.calculateBase(basicSalary, medicalRule);
					newEmp[medicalItem.fieldName] = Number((medicalBase * ratio).toFixed(2));
				}

				// 3. 计算失业保险（个人）- itemId:1990994050818953218
				const unemploymentItem = this.salaryItems.find(item => item.itemId === this.deductionItemIds
					.unemployment);
				const unemploymentRule = this.socialRules[4];
				if (unemploymentItem && unemploymentRule) {
					const ratio = unemploymentItem.ratio || unemploymentRule.personalRatio;
					const unemploymentBase = this.calculateBase(basicSalary, unemploymentRule);
					newEmp[unemploymentItem.fieldName] = Number((unemploymentBase * ratio).toFixed(2));
				}

				// 4. 计算公积金（个人）- itemId:7
				const housingItem = this.salaryItems.find(item => item.itemId === this.deductionItemIds.housingFund);
				const housingRule = this.socialRules[2];
				if (housingItem && housingRule) {
					const ratio = housingItem.ratio || housingRule.personalRatio;
					const housingBase = this.calculateBase(basicSalary, housingRule);
					newEmp[housingItem.fieldName] = Number((housingBase * ratio).toFixed(2));
				}

				// 5. 计算个人所得税
				const taxItem = this.salaryItems.find(item => item.itemId === this.deductionItemIds.incomeTax);
				if (taxItem) {
					const deductionItemIds = [
						this.deductionItemIds.pension,
						this.deductionItemIds.medical,
						this.deductionItemIds.unemployment,
						this.deductionItemIds.housingFund
					];
					const totalDeduction = deductionItemIds.reduce((sum, id) => {
						const item = this.salaryItems.find(i => i.itemId === id);
						return sum + (item ? (newEmp[item.fieldName] || 0) : 0);
					}, 0);

					const taxableIncome = newEmp.payableSalary - totalDeduction - 5000;
					newEmp[taxItem.fieldName] = taxableIncome > 0 ? Number((taxableIncome * 0.03).toFixed(2)) : 0;
				}

				// 计算实发工资
				const allDeductionItems = this.salaryItems.filter(item => !item.isIncome);
				const totalDeduction = allDeductionItems.reduce((sum, item) => {
					return sum + (newEmp[item.fieldName] || 0);
				}, 0);

				newEmp.actualSalary = Number((newEmp.payableSalary - totalDeduction).toFixed(2));
				newEmp.status = "unconfirmed";

				// 添加到列表
				this.employees.push(newEmp);

				// 滚动到最新添加的项
				setTimeout(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select(`.list-item:last-child`).boundingClientRect(rect => {
						if (rect) {
							uni.createSelectorQuery().in(this).select('.salary-list').scrollOffset(
								offset => {
									uni.createSelectorQuery().in(this).select('.salary-list')
										.scrollToOffset({
											scrollTop: offset.scrollTop + rect.top - 200,
											duration: 300
										});
								}).exec();
						}
					}).exec();
				}, 100);
			}
		}
	};
</script>
<style scoped>
	/* 容器样式 */
	.salary-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f7fa;
		overflow: hidden;
	}

	/* 加载状态样式 */
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: calc(100vh - 300rpx);
	}

	.loading-text {
		margin-top: 20rpx;
		font-size: 16px;
		color: #666;
	}

	/* 年月选择器样式 */
	.year-picker-container {
		display: flex;
		justify-content: center;
		padding: 15px 0 10px;
		background-color: #f5f7fa;
	}

	.year-picker {
		width: auto;
	}

	.year-display {
		padding: 6px 18px;
		font-size: 16px;
		color: #ffffff;
		border-radius: 4px;
	}

	.selected {
		background-color: #409eff;
	}

	.month-slider {
		width: 100%;
		white-space: nowrap;
		padding-bottom: 15rpx;
		background-color: #f5f7fa;
	}

	.month-tab {
		width: 140rpx;
		height: 60rpx;
		line-height: 60rpx;
		display: inline-block;
		text-align: center;
		margin: 0 10rpx;
		background-color: #e6f2ff;
		color: #409eff;
		font-size: 15px;
		border-radius: 10rpx;
		background: rgba(222, 235, 255, 1);
	}

	.month-tab-selected {
		background-color: #ffffff;
		color: #409eff;
		border: 2px solid #409eff;
		font-weight: 500;
	}

	/* 空状态样式 */
	.empty-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: calc(100vh - 300rpx);
		padding: 20rpx;
		text-align: center;
	}

	.empty-text {
		margin-top: 20rpx;
		font-size: 16px;
		color: #666;
	}

	.empty-tip {
		margin-top: 10rpx;
		font-size: 14px;
		color: #999;
	}

	/* 编辑弹窗样式 */
	.edit-popup {
		padding: 24rpx;
		background-color: #fff;
		border-radius: 16rpx;
	}

	.popup-title {
		font-size: 20px;
		font-weight: bold;
		text-align: center;
		margin-bottom: 30rpx;
		color: #333;
	}

	.form-group {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.form-label {
		width: 200rpx;
		font-size: 16px;
		color: #666;
	}

	.form-value {
		flex: 1;
		font-size: 16px;
		color: #333;
	}

	.form-actions {
		display: flex;
		justify-content: center;
		gap: 40rpx;
		margin-top: 40rpx;
	}

	.cancel-btn,
	.save-btn {
		width: 200rpx;
		height: 70rpx;
		line-height: 70rpx;
		text-align: center;
		border-radius: 8rpx;
		font-size: 16px;
	}

	.cancel-btn {
		background-color: #f5f5f5;
		color: #666;
	}

	.save-btn {
		background-color: #1677ff;
		color: #fff;
	}

	/* 导航栏样式 */
	.navbar-left {
		display: flex;
		align-items: center;
	}

	.back-button {
		display: flex;
		align-items: center;
	}

	.nav-back-content {
		display: flex;
		align-items: center;
	}

	.nav-title {
		color: #1e88e5;
		font-size: 16px;
		font-weight: 500;
		margin-left: 8px;
	}

	/* 筛选栏样式 */
	.filter-bar {
		padding: 12px 16px;
		background-color: white;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #f0f2f5;
		position: sticky;
		top: 0;
		z-index: 10;
	}

	.status-tabs {
		display: flex;
	}

	.status-tab {
		padding: 6px 18px;
		border-radius: 20px;
		font-size: 14px;
		margin-right: 12px;
		transition: all 0.2s ease;
		cursor: pointer;
	}

	.status-tab.active {
		background-color: #1677ff;
		color: white;
		box-shadow: 0 2px 8px rgba(22, 119, 255, 0.2);
	}

	.status-tab:not(.active) {
		background-color: #f5f7fa;
		color: #666;
	}

	.status-tab:not(.active):active {
		background-color: #e8eaed;
	}

	.action-buttons {
		display: flex;
	}

	.action-btn {
		padding: 6px 16px;
		border-radius: 6px;
		font-size: 14px;
		margin-left: 12px;
		box-sizing: border-box;
		transition: all 0.2s ease;
		cursor: pointer;
	}

	.send-salary {
		background-color: #1677ff;
		color: white;
		border: none;
	}

	.batch-edit,
	.cancel-select {
		background-color: white;
		border: 1px solid #1677ff;
		color: #1677ff;
	}

	/* 工资列表样式 */
	.salary-list {
		flex: 1;
		overflow-y: auto;
		padding-bottom: calc(220rpx + env(safe-area-inset-bottom));
	}

	.list-item {
		background-color: white;
		margin: 10px 16px;
		border-radius: 10px;
		overflow: hidden;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04);
		transition: transform 0.15s ease, box-shadow 0.15s ease;
		position: relative;
		padding-bottom: 80rpx;
	}

	.list-item:active {
		transform: translateY(1px);
		box-shadow: 0 1px 5px rgba(0, 0, 0, 0.03);
	}

	.employee-header {
		padding: 16px;
		border-bottom: 1px solid #f5f7fa;
	}

	.name-status {
		display: flex;
		justify-content: space-between;
		align-items: center;
		flex-wrap: wrap;
	}

	.employee-name {
		font-size: 18px;
		font-weight: 500;
		color: #333;
	}

	.month {
		font-size: 14px;
		color: #999;
		margin-left: 12px;
	}

	.status-tag {
		display: inline-flex;
		align-items: center;
		padding: 4px 10px;
		border-radius: 12px;
		font-size: 12px;
	}

	.status-tag.unentered {
		background-color: #fff2e8;
		color: #fa8c16;
	}

	.status-tag.unconfirmed {
		background-color: #e8f4ff;
		color: #1677ff;
	}

	.status-tag.confirmed {
		background-color: #f0fff4;
		color: #52c41a;
	}

	.status-icon {
		margin-right: 4px;
	}

	/* 工资详情样式 */
	.salary-details {
		padding: 16px;
	}

	.detail-row {
		display: flex;
		justify-content: space-between;
		padding: 8px 0;
		font-size: 14px;
	}

	.detail-label {
		color: #666;
		width: 120rpx;
	}

	.detail-value {
		color: #333;
		text-align: right;
		flex: 1;
	}

	.divider {
		height: 1px;
		background-color: #f5f7fa;
		margin: 12px 0;
	}

	.total-row {
		font-weight: 500;
	}

	.total-row .detail-label {
		color: #333;
	}

	.total-row .detail-value {
		color: #1677ff;
	}

	/* 操作按钮组样式 */
	.action-buttons-group {
		position: absolute;
		bottom: 20rpx;
		right: 20rpx;
		display: flex;
		gap: 20rpx;
		z-index: 1;
	}

	.operate-button {
		display: flex;
		gap: 10rpx;
		align-items: center;
		justify-content: center;
		width: 140rpx;
		height: 60rpx;
		border-radius: 8rpx;
		background-color: #f5f7fa;
		transition: background-color 0.2s ease;
	}

	.operate-button:active {
		background-color: #e8eaed;
	}

	.button-text {
		font-size: 12px;
		margin-left: 4rpx;
	}

	.edit-button {
		background-color: #e8f4ff;
	}

	.confirm-enter-button {
		background-color: #f0fff4;
	}

	.confirm-salary-button {
		background-color: #fff7e6;
	}

	/* 批量选择框样式 */
	.batch-checkbox-group {
		position: absolute;
		/* top: 50%; */
		right: 20rpx;
		transform: translateY(-50%);
	}

	.batch-checkbox {
		width: 36rpx;
		height: 36rpx;
	}

	.stats-container {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: white;
		border-top: 1px solid #f0f2f5;
		z-index: 10;
	}

	.stats-bar {
		padding: 12px 16px;
		padding-bottom: calc(12px + env(safe-area-inset-bottom));
	}

	.total-people {
		color: #1677ff;
		font-size: 14px;
		font-weight: 500;
		margin-bottom: 8px;
	}

	.stats-values {
		display: flex;
		justify-content: space-between;
		align-items: center;
		flex-wrap: wrap;
		gap: 10px;
	}

	.stat-item {
		font-size: 14px;
	}

	.stat-label {
		color: #000;
		font-weight: bold;
		font-size: 15px;
		margin-right: 4px;
	}

	.stat-number {
		color: #e53935;
		font-size: 15px;
	}

	.batch-action-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: auto;
		background-color: white;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 58rpx 16px;
		padding-bottom: calc(12px + env(safe-area-inset-bottom));
		border-top: 1px solid #f0f2f5;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.02);
		z-index: 10;
	}

	.selected-count {
		font-size: 14px;
		color: #666;
	}

	.action-group {
		display: flex;
	}

	.batch-btn {
		padding: 6px 22px;
		border-radius: 6px;
		font-size: 14px;
		margin-left: 12px;
		transition: all 0.2s ease;
		cursor: pointer;
	}

	.confirm-btn {
		background-color: #1677ff;
		color: white;
		border: none;
		padding: 7px 22px;
	}

	.delete-btn {
		background-color: white;
		color: #ff4d4f;
		border: 1px solid #ff4d4f;
	}

	.add-button {
		position: fixed;
		z-index: 9999;
		bottom: calc(85px + env(safe-area-inset-bottom));
		right: 24px;
		width: 52px;
		height: 52px;
		border-radius: 50%;
		background-color: #1677ff;
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4px 16px rgba(22, 119, 255, 0.3);
		transition: all 0.2s ease;
	}

	/* 批量操作底部栏 */
	.batch-action-bar {
		background-color: #ffffff;
		padding: 16rpx 24rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-top: 1px solid #e5e7eb;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 99;
	}

	.selected-count {
		font-size: 26rpx;
		color: #4b5563;
	}

	.action-group {
		display: flex;
		gap: 16rpx;
	}

	.batch-btn {
		display: flex;
		align-items: center;
		gap: 4rpx;
		font-size: 26rpx;
		padding: 8rpx 10rpx;
		border-radius: 32rpx;
		cursor: pointer;
	}

	.btn-icon {
		margin-top: 2rpx;
	}

	.delete-btn {
		background-color: #fef2f2;
		color: #dc2626;
	}

	.confirm-enter-btn {
		background-color: #ecfdf5;
		color: #10b981;
	}

	.confirm-salary-btn {
		background-color: #fff7ed;
		color: #fa8c16;
	}
</style>